// 🚀 CYBER LOADER v4.0 - 量子级核心应用逻辑

let websocket = null;
let clientId = 'cyber_' + Math.random().toString(36).substr(2, 9);
let currentMode = 'video'; // 默认视频模式

// 获取客户端ID的函数
function getClientId() {
    return clientId;
}

// WebSocket连接状态
let isConnected = false;

// 动画和特效控制
let particleAnimation = null;
let glowEffects = [];
let audioContext = null;
let systemStats = {
    cpu: 45,
    ram: 62,
    net: 78,
    downloads: 1247,
    successRate: 98.5,
    avgSpeed: 12.4
};

// 初始化应用
function initApp() {
    console.log('🚀 CYBER LOADER v4.0 量子引擎正在启动...');
    initWebSocket();
    loadSettings();
    initQuantumEffects();
    initInteractionEffects();
    initSystemMonitoring();
    initAudioSystem();
    initKeyboardShortcuts();

    // 加载保存的Cookie
    if (typeof loadSavedCookies === 'function') {
        loadSavedCookies();
    }


}

// 🌟 初始化量子特效系统
function initQuantumEffects() {
    // 初始化高级粒子系统
    initAdvancedParticles();
    
    // 初始化卡片3D效果
    initCard3DEffects();
    
    // 初始化按钮量子动画
    initQuantumButtonEffects();
    
    // 初始化进度条动画
    initProgressAnimations();
    
    // 初始化全息效果
    initHologramEffects();
    
    // 初始化数据流动画
    initDataStreamEffects();
}

// 🎨 高级粒子系统
function initAdvancedParticles() {
    const starfield = document.getElementById('starfield');
    if (!starfield) return;
    
    // 清除现有粒子
    starfield.innerHTML = '';
    
    const particleCount = 80;
    const particles = [];
    
    for (let i = 0; i < particleCount; i++) {
        const particle = document.createElement('div');
        particle.className = 'particle';
        
        // 随机属性
        const size = Math.random() * 6 + 2;
        const x = Math.random() * 100;
        const y = Math.random() * 100;
        const delay = Math.random() * 8;
        const duration = Math.random() * 6 + 4;
        
        // 随机颜色（科技蓝色系）
        const colors = ['#00d4ff', '#667eea', '#764ba2', '#f093fb', '#ff6b9d'];
        const color = colors[Math.floor(Math.random() * colors.length)];
        
        particle.style.cssText = `
            left: ${x}%;
            top: ${y}%;
            width: ${size}px;
            height: ${size}px;
            background: ${color};
            animation-delay: ${delay}s;
            animation-duration: ${duration}s;
            box-shadow: 0 0 ${size * 2}px ${color};
        `;
        
        starfield.appendChild(particle);
        particles.push(particle);
    }
    
    // 粒子互动效果
    document.addEventListener('mousemove', (e) => {
        const mouseX = e.clientX / window.innerWidth * 100;
        const mouseY = e.clientY / window.innerHeight * 100;
        
        particles.forEach((particle, index) => {
            const rect = particle.getBoundingClientRect();
            const particleX = (rect.left + rect.width / 2) / window.innerWidth * 100;
            const particleY = (rect.top + rect.height / 2) / window.innerHeight * 100;
            
            const distance = Math.sqrt(
                Math.pow(mouseX - particleX, 2) + Math.pow(mouseY - particleY, 2)
            );
            
            if (distance < 15) {
                particle.style.transform = `scale(${1.5 - distance / 30})`;
                particle.style.opacity = Math.max(0.3, 1 - distance / 15);
            } else {
                particle.style.transform = 'scale(1)';
                particle.style.opacity = '0.6';
            }
        });
    });
}

// 🎯 卡片3D特效系统
function initCard3DEffects() {
    const cards = document.querySelectorAll('.card');
    
    cards.forEach((card, index) => {
        // 创建3D倾斜效果

        

        
        // 设置卡片初始状态
        card.style.opacity = '1';
    });
}



// 🎛️ 量子按钮特效系统
function initQuantumButtonEffects() {
    const buttons = document.querySelectorAll('.btn');
    
    buttons.forEach(button => {
        // 量子波纹效果
        button.addEventListener('click', (e) => {
            createQuantumRipple(button, e);
            playQuantumSound('click');
        });
        
        // 悬停粒子效果
        button.addEventListener('mouseenter', () => {
            button.style.filter = 'brightness(1.15) saturate(1.3)';
            createButtonParticles(button);
            playQuantumSound('hover');
        });
        
        button.addEventListener('mouseleave', () => {
            button.style.filter = 'brightness(1) saturate(1)';
            removeButtonParticles(button);
        });
        
        // 长按充能效果
        let pressTimer;
        button.addEventListener('mousedown', () => {
            pressTimer = setTimeout(() => {
                createChargeEffect(button);
            }, 500);
        });
        
        button.addEventListener('mouseup', () => {
            clearTimeout(pressTimer);
        });
        
        button.addEventListener('mouseleave', () => {
            clearTimeout(pressTimer);
        });
    });
}

// 创建量子波纹
function createQuantumRipple(button, e) {
    const ripple = document.createElement('span');
    const rect = button.getBoundingClientRect();
    const size = Math.max(rect.width, rect.height) * 1.5;
    const x = e.clientX - rect.left - size / 2;
    const y = e.clientY - rect.top - size / 2;
    
    ripple.style.cssText = `
        position: absolute;
        width: ${size}px;
        height: ${size}px;
        left: ${x}px;
        top: ${y}px;
        background: radial-gradient(circle, rgba(0,212,255,0.6) 0%, rgba(255,255,255,0.3) 50%, transparent 100%);
        border-radius: 50%;
        transform: scale(0);
        animation: quantumRipple 0.8s cubic-bezier(0.23, 1, 0.32, 1);
        pointer-events: none;
        z-index: 10;
    `;
    
    button.style.position = 'relative';
    button.style.overflow = 'hidden';
    button.appendChild(ripple);
    
    setTimeout(() => {
        ripple.remove();
    }, 800);
}

// 创建按钮粒子效果
function createButtonParticles(button) {
    const particleCount = 8;
    const rect = button.getBoundingClientRect();
    
    for (let i = 0; i < particleCount; i++) {
        const particle = document.createElement('div');
        particle.className = 'button-particle';
        
        const angle = (i / particleCount) * Math.PI * 2;
        const radius = 50;
        const x = Math.cos(angle) * radius;
        const y = Math.sin(angle) * radius;
        
        particle.style.cssText = `
            position: absolute;
            width: 4px;
            height: 4px;
            background: #00d4ff;
            border-radius: 50%;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            animation: particleOrbit 2s linear infinite;
            animation-delay: ${i * 0.1}s;
            box-shadow: 0 0 10px #00d4ff;
            z-index: 5;
        `;
        
        button.appendChild(particle);
    }
}

// 移除按钮粒子
function removeButtonParticles(button) {
    const particles = button.querySelectorAll('.button-particle');
    particles.forEach(particle => {
        particle.style.animation = 'particleFadeOut 0.3s ease-out forwards';
        setTimeout(() => {
            if (particle.parentNode) {
                particle.parentNode.removeChild(particle);
            }
        }, 300);
    });
}

// 创建充能效果
function createChargeEffect(button) {
    const charge = document.createElement('div');
    charge.className = 'charge-effect';
    charge.style.cssText = `
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: linear-gradient(45deg, transparent, rgba(0,212,255,0.3), transparent);
        border-radius: inherit;
        animation: chargeFlow 1s ease-in-out infinite;
        pointer-events: none;
        z-index: 2;
    `;
    
    button.appendChild(charge);
    
    setTimeout(() => {
        if (charge.parentNode) {
            charge.parentNode.removeChild(charge);
        }
    }, 2000);
}

// 添加量子动画样式
const quantumStyles = document.createElement('style');
quantumStyles.textContent = `
    @keyframes quantumRipple {
        0% {
            transform: scale(0);
            opacity: 0.8;
        }
        50% {
            opacity: 0.4;
        }
        100% {
            transform: scale(1);
            opacity: 0;
        }
    }
    
    @keyframes particleOrbit {
        0% {
            transform: translate(-50%, -50%) rotate(0deg) translateX(30px) rotate(0deg);
        }
        100% {
            transform: translate(-50%, -50%) rotate(360deg) translateX(30px) rotate(-360deg);
        }
    }
    
    @keyframes particleFadeOut {
        to {
            opacity: 0;
            transform: translate(-50%, -50%) scale(0);
        }
    }
    
    @keyframes chargeFlow {
        0%, 100% {
            transform: translateX(-100%);
        }
        50% {
            transform: translateX(100%);
        }
    }
`;
document.head.appendChild(quantumStyles);

// 📊 进度条动画
function initProgressAnimations() {
    const progressBars = document.querySelectorAll('.progress-fill');
    
    progressBars.forEach(bar => {
        // 脉冲效果
        bar.style.position = 'relative';
        
        const pulse = document.createElement('div');
        pulse.style.cssText = `
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
            animation: progressPulse 2s infinite;
        `;
        
        bar.appendChild(pulse);
    });
    
    // 添加脉冲动画
    const style = document.createElement('style');
    style.textContent = `
        @keyframes progressPulse {
            0% { transform: translateX(-100%); }
            100% { transform: translateX(100%); }
        }
    `;
    document.head.appendChild(style);
}

// 🎮 交互效果初始化
function initInteractionEffects() {
    // 鼠标跟随光标效果
    let cursor = null;
    
    document.addEventListener('mousemove', (e) => {
        if (!cursor) {
            cursor = document.createElement('div');
            cursor.style.cssText = `
                position: fixed;
                width: 20px;
                height: 20px;
                background: radial-gradient(circle, rgba(0,212,255,0.8) 0%, transparent 70%);
                border-radius: 50%;
                pointer-events: none;
                z-index: 9999;
                mix-blend-mode: screen;
                transition: all 0.1s ease;
            `;
            document.body.appendChild(cursor);
        }
        
        cursor.style.left = (e.clientX - 10) + 'px';
        cursor.style.top = (e.clientY - 10) + 'px';
    });
    
    // 键盘快捷键
    document.addEventListener('keydown', (e) => {
        if (e.ctrlKey) {
            switch (e.key) {
                case '1':
                    e.preventDefault();
                    switchPage('douyin');
                    break;
                case '2':
                    e.preventDefault();
                    switchPage('kuaishou');
                    break;
                case '3':
                    e.preventDefault();
                    switchPage('vmq');
                    break;
                case '4':
                    e.preventDefault();
                    switchPage('settings');
                    break;
                case '5':
                    e.preventDefault();
                    switchPage('help');
                    break;
            }
        }
    });
    
    // 滚动视差效果
    window.addEventListener('scroll', () => {
        const scrolled = window.pageYOffset;
        const parallax = document.querySelector('.hologram-grid');
        if (parallax) {
            parallax.style.transform = `translateY(${scrolled * 0.5}px)`;
        }
    });
}

// 获取当前日志区域（增强版）
function getCurrentLogArea() {
    const activePage = document.querySelector('.page.active');
    if (!activePage) return document.getElementById('logArea');
    
    const pageId = activePage.id;
    
    switch (pageId) {
        case 'douyinPage':
            return document.getElementById('logArea');
        case 'kuaishouPage':
            return document.getElementById('kuaishouLogArea');
        case 'vmqPage':
            const activeVmqContent = document.querySelector('.vmq-content.active');
            if (activeVmqContent) {
                const vmqMode = activeVmqContent.id;
                switch (vmqMode) {
                    case 'vmqSingle':
                        return document.getElementById('vmqLogArea');
                    case 'vmqBatch':
                        return document.getElementById('vmqBatchLogArea');
                    case 'vmqTiefenquan':
                        return document.getElementById('tiefenquanLogArea');
                    case 'vmqTiefenquanVideo':
                        return document.getElementById('tiefenquanVideoLogArea');
                }
            }
            return document.getElementById('vmqLogArea');
        case 'settingsPage':
            return document.getElementById('settingsLogArea');
        default:
            return document.getElementById('logArea');
    }
}

// 添加日志条目（增强版）
function addLogEntry(message, type = 'info') {
    const logArea = getCurrentLogArea();
    if (!logArea) return;
    
    const logEntry = document.createElement('div');
    logEntry.className = `log-entry ${type}`;
    
    const timestamp = new Date().toLocaleTimeString();
    
    // 添加图标
    const icons = {
        info: '💡',
        success: '✅',
        error: '❌',
        warning: '⚠️'
    };
    
    logEntry.innerHTML = `
        <span class="log-time">[${timestamp}]</span>
        <span>${icons[type] || '💡'} ${message}</span>
    `;
    
    // 添加入场动画
    logEntry.style.opacity = '0';
    logEntry.style.transform = 'translateX(-20px)';
    
    logArea.appendChild(logEntry);
    
    // 设置日志条目状态
    logEntry.style.opacity = '1';
    
    // 自动滚动到底部
    logArea.scrollTop = logArea.scrollHeight;
    
    // 限制日志条目数量
    const entries = logArea.querySelectorAll('.log-entry');
    if (entries.length > 100) {
        entries[0].remove();
    }
}

// 清空日志（增强版）
function clearLog() {
    const logArea = getCurrentLogArea();
    if (logArea) {
        // 淡出动画
        logArea.style.opacity = '0.3';
        
        setTimeout(() => {
        logArea.innerHTML = `
                <div class="log-entry info" style="left: -17px;">
                <span class="log-time">[${new Date().toLocaleTimeString()}]</span>
                    <span>🧹 系统日志已清空，准备接收新任务...</span>
            </div>
        `;
            logArea.style.opacity = '1';
        }, 200);
    }
}

// 更新进度条（增强版）
function updateProgress(progress) {
    const activePage = document.querySelector('.page.active');
    if (!activePage) return;
    
    const pageId = activePage.id;
    let progressFill, progressText;
    
    switch (pageId) {
        case 'douyinPage':
            progressFill = document.getElementById('progressFill');
            progressText = document.getElementById('progressText');
            break;
        case 'kuaishouPage':
            progressFill = document.getElementById('kuaishouProgressFill');
            progressText = document.getElementById('kuaishouProgressText');
            break;
        case 'vmqPage':
            const activeVmqContent = document.querySelector('.vmq-content.active');
            if (activeVmqContent) {
                const vmqMode = activeVmqContent.id;
                switch (vmqMode) {
                    case 'vmqSingle':
                        progressFill = document.getElementById('vmqProgressFill');
                        progressText = document.getElementById('vmqProgressText');
                        break;
                    case 'vmqBatch':
                        progressFill = document.getElementById('vmqBatchProgressFill');
                        progressText = document.getElementById('vmqBatchProgressText');
                        break;
                    case 'vmqTiefenquan':
                        progressFill = document.getElementById('tiefenquanProgressFill');
                        progressText = document.getElementById('tiefenquanProgressText');
                        break;
                    case 'vmqTiefenquanVideo':
                        progressFill = document.getElementById('tiefenquanVideoProgressFill');
                        progressText = document.getElementById('tiefenquanVideoProgressText');
                        break;
                }
            }
            break;
    }
    
    if (progressFill && progressText) {
        // 平滑动画
        progressFill.style.transition = 'width 0.5s ease';
        progressFill.style.width = progress + '%';
        
        // 动态文本和颜色
        let statusText = '';
        let glowColor = '';
        
        if (progress === 0) {
            statusText = '🎯 准备就绪';
            glowColor = 'rgba(0, 212, 255, 0.5)';
        } else if (progress < 30) {
            statusText = `🚀 启动中 ${progress}%`;
            glowColor = 'rgba(102, 126, 234, 0.5)';
        } else if (progress < 70) {
            statusText = `⚡ 处理中 ${progress}%`;
            glowColor = 'rgba(240, 147, 251, 0.5)';
        } else if (progress < 100) {
            statusText = `🔥 即将完成 ${progress}%`;
            glowColor = 'rgba(255, 107, 157, 0.5)';
        } else {
            statusText = '✨ 任务完成';
            glowColor = 'rgba(0, 255, 136, 0.5)';
        }
        
        progressText.textContent = statusText;
        progressFill.style.boxShadow = `0 0 20px ${glowColor}`;
    }
}

// 🎵 音效系统（可选）
function playNotificationSound(type = 'success') {
    // 创建音频上下文
    if (typeof AudioContext !== 'undefined' || typeof webkitAudioContext !== 'undefined') {
        const audioContext = new (AudioContext || webkitAudioContext)();
        const oscillator = audioContext.createOscillator();
        const gainNode = audioContext.createGain();
        
        oscillator.connect(gainNode);
        gainNode.connect(audioContext.destination);
        
        // 根据类型设置不同的音调
        const frequencies = {
            success: [523, 659, 784], // C5, E5, G5
            error: [349, 293, 246],   // F4, D4, B3
            warning: [440, 554, 659], // A4, C#5, E5
            info: [523, 659]          // C5, E5
        };
        
        const freq = frequencies[type] || frequencies.info;
        
        oscillator.frequency.setValueAtTime(freq[0], audioContext.currentTime);
        gainNode.gain.setValueAtTime(0.1, audioContext.currentTime);
        gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.3);
        
        oscillator.start(audioContext.currentTime);
        oscillator.stop(audioContext.currentTime + 0.3);
    }
}

// 🎵 量子音效系统
function initAudioSystem() {
    try {
        audioContext = new (AudioContext || webkitAudioContext)();
    } catch (e) {
        console.log('音频系统不可用');
    }
}

// 播放量子音效
function playQuantumSound(type) {
    if (!audioContext) return;
    
    const oscillator = audioContext.createOscillator();
    const gainNode = audioContext.createGain();
    
    oscillator.connect(gainNode);
    gainNode.connect(audioContext.destination);
    
    const frequencies = {
        click: [523, 659, 784],     // C5, E5, G5
        hover: [440, 554],          // A4, C#5
        success: [659, 784, 988],   // E5, G5, B5
        error: [349, 293, 246],     // F4, D4, B3
        notification: [784, 988, 1175] // G5, B5, D6
    };
    
    const freq = frequencies[type] || frequencies.click;
    
    oscillator.frequency.setValueAtTime(freq[0], audioContext.currentTime);
    if (freq[1]) {
        oscillator.frequency.exponentialRampToValueAtTime(freq[1], audioContext.currentTime + 0.1);
    }
    if (freq[2]) {
        oscillator.frequency.exponentialRampToValueAtTime(freq[2], audioContext.currentTime + 0.2);
    }
    
    gainNode.gain.setValueAtTime(0.05, audioContext.currentTime);
    gainNode.gain.exponentialRampToValueAtTime(0.001, audioContext.currentTime + 0.3);
    
    oscillator.start(audioContext.currentTime);
    oscillator.stop(audioContext.currentTime + 0.3);
}

// 🖥️ 系统监控系统
function initSystemMonitoring() {
    // 更新系统统计
    updateSystemStats();
    
    // 每5秒更新一次系统状态
    setInterval(updateSystemStats, 5000);
    
    // 实时更新下载统计
    setInterval(updateDownloadStats, 2000);
}

// 更新系统统计
function updateSystemStats() {
    // 模拟系统负载变化
    systemStats.cpu = Math.max(20, Math.min(95, systemStats.cpu + (Math.random() - 0.5) * 10));
    systemStats.ram = Math.max(30, Math.min(90, systemStats.ram + (Math.random() - 0.5) * 8));
    systemStats.net = Math.max(40, Math.min(100, systemStats.net + (Math.random() - 0.5) * 15));
    
    // 更新侧边栏统计
    const cpuBar = document.querySelector('.stat-item:nth-child(1) .stat-fill');
    const ramBar = document.querySelector('.stat-item:nth-child(2) .stat-fill');
    const netBar = document.querySelector('.stat-item:nth-child(3) .stat-fill');
    
    if (cpuBar) cpuBar.style.width = systemStats.cpu + '%';
    if (ramBar) ramBar.style.width = systemStats.ram + '%';
    if (netBar) netBar.style.width = systemStats.net + '%';
}

// 更新下载统计
function updateDownloadStats() {
    // 模拟下载统计变化
    if (Math.random() > 0.7) {
        systemStats.downloads += Math.floor(Math.random() * 3) + 1;
        systemStats.successRate = Math.max(95, Math.min(99.9, systemStats.successRate + (Math.random() - 0.5) * 0.5));
        systemStats.avgSpeed = Math.max(8, Math.min(25, systemStats.avgSpeed + (Math.random() - 0.5) * 2));
    }
    
    // 更新页面统计显示
    const downloadElement = document.getElementById('douyinTotalDownloads');
    const successElement = document.getElementById('douyinSuccessRate');
    const speedElement = document.getElementById('douyinSpeed');
    
    if (downloadElement) {
        downloadElement.textContent = systemStats.downloads.toLocaleString();
        downloadElement.style.animation = 'none';
        downloadElement.offsetHeight; // 触发重排
        downloadElement.style.animation = 'numberUpdate 0.5s ease-out';
    }
    
    if (successElement) {
        successElement.textContent = systemStats.successRate.toFixed(1) + '%';
    }
    
    if (speedElement) {
        speedElement.textContent = systemStats.avgSpeed.toFixed(1) + 'MB/s';
    }
}

// 🌟 全息效果系统
function initHologramEffects() {
    // 为标题添加全息效果
    const titles = document.querySelectorAll('.card-title, .page-title h1, .logo-text');
    
    titles.forEach(title => {
        // 创建全息扫描线
        const scanline = document.createElement('div');
        scanline.className = 'hologram-scanline';
        scanline.style.cssText = `
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 2px;
            background: linear-gradient(90deg, transparent, #00d4ff, transparent);
            animation: hologramScan 3s linear infinite;
            pointer-events: none;
            z-index: 1;
        `;
        
        title.style.position = 'relative';
        title.appendChild(scanline);
        
        // 添加全息闪烁效果
        title.addEventListener('mouseenter', () => {
            title.style.animation = 'hologramFlicker 0.1s ease-in-out 3';
        });
    });
    
    // 添加全息样式
    const hologramStyles = document.createElement('style');
    hologramStyles.textContent = `
        @keyframes hologramScan {
            0% { top: 0%; opacity: 0; }
            50% { opacity: 1; }
            100% { top: 100%; opacity: 0; }
        }
        
        @keyframes hologramFlicker {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.8; text-shadow: 0 0 30px currentColor; }
        }
        
        @keyframes numberUpdate {
            0% { transform: scale(1); }
            50% { transform: scale(1.1); color: #00ff88; }
            100% { transform: scale(1); }
        }
    `;
    document.head.appendChild(hologramStyles);
}

// 📊 数据流动画系统（优化滚动支持）
function initDataStreamEffects() {
    // 为日志容器添加数据流效果
    const logContainers = document.querySelectorAll('.log-container');

    logContainers.forEach(container => {
        // 检查是否已经有数据流背景
        if (container.querySelector('.data-stream')) {
            return;
        }

        // 创建数据流背景
        const dataStream = document.createElement('div');
        dataStream.className = 'data-stream';
        dataStream.style.cssText = `
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background:
                linear-gradient(90deg, transparent 0%, rgba(0,212,255,0.08) 50%, transparent 100%),
                linear-gradient(0deg, transparent 0%, rgba(0,255,136,0.04) 50%, transparent 100%);
            background-size: 200px 100%, 100% 200px;
            background-attachment: local;
            animation: dataFlow 4s linear infinite;
            pointer-events: none;
            z-index: 0;
            border-radius: inherit;
            overflow: hidden;
        `;

        container.style.position = 'relative';
        container.appendChild(dataStream);

        // 创建滚动感知的背景特效
        let animationId = null;

        const updateDataStream = () => {
            const scrollTop = container.scrollTop;
            const scrollHeight = container.scrollHeight;
            const clientHeight = container.clientHeight;

            if (scrollHeight > clientHeight) {
                // 有滚动条时的处理
                const scrollPercent = scrollTop / (scrollHeight - clientHeight);

                // 调整背景位置以跟随滚动
                const offsetY = -scrollTop * 0.3; // 视差效果
                dataStream.style.backgroundPosition = `0px ${offsetY}px, 0px ${offsetY}px`;

                // 根据滚动位置调整透明度
                const opacity = Math.max(0.2, 0.8 - scrollPercent * 0.4);
                dataStream.style.opacity = opacity;
            } else {
                // 没有滚动条时恢复默认
                dataStream.style.backgroundPosition = '';
                dataStream.style.opacity = '0.6';
            }
        };

        // 监听滚动事件
        container.addEventListener('scroll', () => {
            if (animationId) {
                cancelAnimationFrame(animationId);
            }
            animationId = requestAnimationFrame(updateDataStream);
        });

        // 监听内容变化
        const observer = new MutationObserver(() => {
            updateDataStream();
        });

        observer.observe(container, {
            childList: true,
            subtree: true,
            characterData: true
        });

        // 初始化
        updateDataStream();
    });

    // 添加数据流样式
    if (!document.getElementById('dataStreamStyles')) {
        const dataStreamStyles = document.createElement('style');
        dataStreamStyles.id = 'dataStreamStyles';
        dataStreamStyles.textContent = `
            @keyframes dataFlow {
                0% {
                    background-position: -200px 0%, 0% -200px;
                }
                100% {
                    background-position: 200px 0%, 0% 200px;
                }
            }

            .data-stream {
                transition: opacity 0.3s ease;
            }

            /* 确保日志容器的滚动条在背景特效之上 */
            .log-container {
                z-index: 1;
            }

            .log-container .log-entry {
                position: relative;
                z-index: 2;
            }
        `;
        document.head.appendChild(dataStreamStyles);
    }
}

// 🔄 重新初始化数据流特效（用于页面切换后）
function reinitDataStreamEffects() {
    // 移除现有的数据流特效
    document.querySelectorAll('.data-stream').forEach(stream => {
        stream.remove();
    });

    // 重新初始化
    setTimeout(() => {
        initDataStreamEffects();
    }, 100);
}

// ⌨️ 键盘快捷键系统
function initKeyboardShortcuts() {
    document.addEventListener('keydown', (e) => {
        // Ctrl + 数字键切换页面
        if (e.ctrlKey) {
            switch (e.key) {
                case '1':
                    e.preventDefault();
                    switchPage('douyin');
                    playQuantumSound('click');
                    break;
                case '2':
                    e.preventDefault();
                    switchPage('kuaishou');
                    playQuantumSound('click');
                    break;
                case '3':
                    e.preventDefault();
                    switchPage('vmq');
                    playQuantumSound('click');
                    break;
                case '4':
                    e.preventDefault();
                    switchPage('settings');
                    playQuantumSound('click');
                    break;
                case '5':
                    e.preventDefault();
                    switchPage('help');
                    playQuantumSound('click');
                    break;
            }
        }
        
        // ESC键清空当前日志
        if (e.key === 'Escape') {
            clearLog();
            playQuantumSound('notification');
        }
        
        // F11切换全屏
        if (e.key === 'F11') {
            e.preventDefault();
            toggleFullscreen();
        }
    });
}

// 切换全屏模式
function toggleFullscreen() {
    if (!document.fullscreenElement) {
        document.documentElement.requestFullscreen();
        addLogEntry('🔲 已进入全屏模式', 'info');
    } else {
        document.exitFullscreen();
        addLogEntry('🔳 已退出全屏模式', 'info');
    }
}

// 🔧 全局函数检查和定义
(function() {
    console.log('🔧 开始检查和定义全局函数...');
    
    // 确保所有函数都在全局作用域中可用
    if (typeof window.loadSettings === 'undefined') {
        window.loadSettings = function() {
            console.log('📋 加载用户设置...');
            // 这里可以从本地存储或服务器加载设置
        };
    }
    
    if (typeof window.showToast === 'undefined') {
        window.showToast = function(message, type = 'info') {
            // 创建toast提示
            const toast = document.createElement('div');
            toast.className = `toast toast-${type}`;
            toast.textContent = message;
            toast.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: rgba(0, 0, 0, 0.8);
                color: white;
                padding: 12px 20px;
                border-radius: 8px;
                border-left: 4px solid var(--quantum-${type === 'success' ? 'accent' : type === 'error' ? 'danger' : 'primary'});
                z-index: 10000;
                animation: slideInRight 0.3s ease-out;
            `;
            
            document.body.appendChild(toast);
            setTimeout(() => {
                toast.style.animation = 'slideOutRight 0.3s ease-out';
                setTimeout(() => toast.remove(), 300);
            }, 3000);
        };
    }
    
    // 添加toast动画样式
    if (!document.querySelector('#toast-styles')) {
        const toastStyles = document.createElement('style');
        toastStyles.id = 'toast-styles';
        toastStyles.textContent = `
            @keyframes slideInRight {
                from { transform: translateX(100%); opacity: 0; }
                to { transform: translateX(0); opacity: 1; }
            }
            @keyframes slideOutRight {
                from { transform: translateX(0); opacity: 1; }
                to { transform: translateX(100%); opacity: 0; }
            }
        `;
        document.head.appendChild(toastStyles);
    }
    
    // 确保所有关键函数都在全局作用域中
    const globalFunctions = {
        'switchPage': function(pageId) {
            console.log('🔄 全局switchPage被调用:', pageId);
            if (typeof window.performPageSwitch === 'function') {
                window.performPageSwitch(pageId);
            } else {
                console.error('❌ performPageSwitch函数未找到');
            }
        },
        'switchMode': function(mode) {
            console.log('🔄 全局switchMode被调用:', mode);
            // 这里可以添加模式切换逻辑
        },
        'checkAuthenticationStatus': function() {
            console.log('🔄 全局checkAuthenticationStatus被调用');
            return false; // 默认返回false
        }
    };
    
    // 将函数添加到全局作用域
    Object.keys(globalFunctions).forEach(funcName => {
        if (typeof window[funcName] === 'undefined') {
            window[funcName] = globalFunctions[funcName];
            console.log(`✅ 添加全局函数: ${funcName}`);
        }
    });
    
    console.log('✅ 全局函数检查完成');
})();

// 🔧 缺失函数定义
function loadSettings() {
    console.log('📋 加载用户设置...');
    // 这里可以从本地存储或服务器加载设置
}

function showToast(message, type = 'info') {
    // 创建toast提示
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.textContent = message;
    toast.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: rgba(0, 0, 0, 0.8);
        color: white;
        padding: 12px 20px;
        border-radius: 8px;
        border-left: 4px solid var(--quantum-${type === 'success' ? 'accent' : type === 'error' ? 'danger' : 'primary'});
        z-index: 10000;
        animation: slideInRight 0.3s ease-out;
    `;
    
    document.body.appendChild(toast);
    setTimeout(() => {
        toast.style.animation = 'slideOutRight 0.3s ease-out';
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}

// 添加toast动画样式
const toastStyles = document.createElement('style');
toastStyles.textContent = `
    @keyframes slideInRight {
        from { transform: translateX(100%); opacity: 0; }
        to { transform: translateX(0); opacity: 1; }
    }
    @keyframes slideOutRight {
        from { transform: translateX(0); opacity: 1; }
        to { transform: translateX(100%); opacity: 0; }
    }
`;
document.head.appendChild(toastStyles);

// 文件选择器相关函数 - 这些函数在file-selector.js中已定义
// 这里保留为备用，如果file-selector.js未加载则使用这些函数
if (typeof browsePath === 'undefined') {
    function browsePath() {
        showToast('💡 请手动输入保存路径，或使用默认路径', 'info');
    }
}

if (typeof browseKuaishouPath === 'undefined') {
    function browseKuaishouPath() {
        showToast('💡 请手动输入保存路径，或使用默认路径', 'info');
    }
}

if (typeof browseVmqPath === 'undefined') {
    function browseVmqPath() {
        showToast('💡 请手动输入保存路径，或使用默认路径', 'info');
    }
}

if (typeof browseVmqBatchPath === 'undefined') {
    function browseVmqBatchPath() {
        showToast('💡 请手动输入保存路径，或使用默认路径', 'info');
    }
}

if (typeof browseTiefenquanPath === 'undefined') {
    function browseTiefenquanPath() {
        showToast('💡 请手动输入保存路径，或使用默认路径', 'info');
    }
}

// 设置页面相关函数
function testProxy() {
    const proxyHost = document.getElementById('proxyHost').value;
    const proxyPort = document.getElementById('proxyPort').value;
    
    if (!proxyHost || !proxyPort) {
        showToast('❌ 请填写代理地址和端口', 'error');
        return;
    }
    
    showToast('🧪 正在测试代理连接...', 'info');
    
    // 模拟测试结果
    setTimeout(() => {
        const isSuccess = Math.random() > 0.3; // 70%成功率
        if (isSuccess) {
            showToast('✅ 代理连接测试成功', 'success');
        } else {
            showToast('❌ 代理连接测试失败', 'error');
        }
    }, 2000);
}

function saveProxySettings() {
    showToast('💾 代理设置已保存', 'success');
}

function updateCookies() {
    const platformSelect = document.getElementById('platformSelect');
    const cookieInput = document.getElementById('cookieInput');
    
    if (!cookieInput.value.trim()) {
        showToast('❌ 请输入Cookie数据', 'error');
        return;
    }
    
    const platform = platformSelect.value;
    showToast(`🔄 ${platform}平台Cookie已更新`, 'success');
}

function clearCookies() {
    const cookieInput = document.getElementById('cookieInput');
    cookieInput.value = '';
    showToast('🗑️ Cookie已清空', 'success');
}

function saveAdvancedSettings() {
    showToast('💾 高级设置已保存', 'success');
}

function resetSettings() {
    const threadCount = document.getElementById('threadCount');
    const timeout = document.getElementById('timeout');
    const autoRetry = document.getElementById('autoRetry');
    
    if (threadCount) threadCount.value = '5';
    if (timeout) timeout.value = '30';
    if (autoRetry) autoRetry.checked = true;
    
    showToast('🔄 设置已重置为默认值', 'success');
}

// 清空日志函数的补充
function clearKuaishouLog() {
    const logArea = document.getElementById('kuaishouLogArea');
    if (logArea) {
        logArea.style.opacity = '0.3';
        setTimeout(() => {
            logArea.innerHTML = `
                <div class="log-entry info">
                    <span class="log-time">[${new Date().toLocaleTimeString()}]</span>
                    <span>🧹 快手日志已清空，准备接收新任务...</span>
                </div>
            `;
            logArea.style.opacity = '1';
        }, 200);
    }
}

function clearVmqLog() {
    const logArea = document.getElementById('vmqLogArea');
    if (logArea) {
        logArea.style.opacity = '0.3';
        setTimeout(() => {
            logArea.innerHTML = `
                <div class="log-entry info">
                    <span class="log-time">[${new Date().toLocaleTimeString()}]</span>
                    <span>🧹 微密圈日志已清空，准备接收新任务...</span>
                </div>
            `;
            logArea.style.opacity = '1';
        }, 200);
    }
}

// 🚀 启动应用
document.addEventListener('DOMContentLoaded', function() {
    console.log('🌟 正在初始化 CYBER LOADER v4.0...');
    
    // 初始化应用
    document.body.style.opacity = '1';
    
    if (typeof initApp === 'function') {
        initApp();
    } else {
        console.error('❌ initApp函数未找到');
    }
    
    console.log('✨ CYBER LOADER v4.0 量子引擎启动完成！');
    
    // 显示欢迎消息
    setTimeout(() => {
        if (typeof addLogEntry === 'function') {
            addLogEntry('🚀 欢迎使用 CYBER LOADER v4.0 量子级下载引擎！', 'success');
            addLogEntry('💡 快捷键: Ctrl+1~5 切换页面, ESC 清空日志, F11 全屏', 'info');
            addLogEntry('🎵 量子音效系统已激活', 'info');
        }
        if (typeof playQuantumSound === 'function') {
            playQuantumSound('success');
        }
    }, 1000);
});